// import { stringify } from 'qs';
import JSEncrypt from 'jsencrypt';
import request from '../utils/request';
import { ipConfig } from './config';
import { Constants } from '../utils';

const PATH = '/api-ms/authorize';

// 刷新验证码
const refreshSecurityUrl = `/api-ms/system/securityCode?appId=APP_RXSB&userCode=`;

const AuthCode = {
  clientAppId: Constants.APP_ID,
  securityCode: '',
};

export const login = async params => {
  const encrypt = new JSEncrypt();
  encrypt.setPublicKey(Constants.RSA_PUBLICKEY);
  const password = encrypt.encrypt(params.password);
  const defaultParams = AuthCode;
  const newParams = { ...defaultParams, ...params, password };
  return request(`${ipConfig.url(PATH)}/login`, {
    method: 'POST',
    body: newParams,
  })
    .then(mapToken)
    .catch(error => {
      const token = {
        access: false,
        error,
      };
      return token;
    });
};

export const refreshSecurity = async (account) => request(`${ipConfig.url(refreshSecurityUrl)}${account}`, {
  method: 'GET',
}).then(response => {
  console.info(response);
  const res = {
    success: true,
    data: response,
  };
  return res;
}).catch(error => {
  const res = {
    success: false,
    error,
  };
  return res;
});

const mapToken = response => {
  const token = {
    access: response.access_token,
    refresh: response.refresh_token,
  };
  return token;
};

// http://facebook.github.io/react-native/movies.json
// export const login = async () => request(`${bashUrl}/login`, {
//   method: 'GET',
// });
